{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 打印所有单行变量\n",
    "from IPython.core.interactiveshell import InteractiveShell\n",
    "InteractiveShell.ast_node_interactivity = 'all'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## python3基础语法\n",
    "python是一种解释型语言\n",
    "\n",
    "### Linux环境下编程\n",
    "打开终端输入python3即可进入python3 shell，要打开py文件直接在py文件所在位置终端输入python3 ***.py，或输入绝对路径打开"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "23.0\n"
     ]
    }
   ],
   "source": [
    "#!/usr/bin/env python3  # linux系统下必须，这是python3的环境变量\n",
    "#coding:utf-8  # 申明编码，非必须，便于阅读和维护\n",
    "\n",
    "a = 19 + 2 * 4 - 8 / 2  # 表达式\n",
    "print(a)  # 函数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 编译\n",
    "当运行`.py`文件的时候，Python会通过编译器，将它编译为`.pyc`文件。\n",
    "然后这个文件就在一个名为虚拟机的东西上运行，这个所谓的虚拟机是专门为Python设计的。有了虚拟机，使得Python可以跨平台\n",
    "\n",
    "### 编码\n",
    "默认情况下，Python 3 源码文件以 UTF-8 编码，所有字符串都是 unicode 字符串。也可以为源码文件指定不同的编码：\n",
    "    \n",
    "    # -*- coding: cp-1252 -*-\n",
    "\n",
    "### 标识符(给对象起名字)\n",
    "> 一切皆可为对象\n",
    "* 第一个字符必须是字母表中字母或下划线`_`。\n",
    "* 标识符的其他的部分有字母、数字和下划线组成。\n",
    "* 标识符对大小写敏感。\n",
    "\n",
    "### python保留字"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']\n"
     ]
    }
   ],
   "source": [
    "import keyword\n",
    "\n",
    "print(keyword.kwlist)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 注释\n",
    "> 注释的作用便于读写和维护代码\n",
    "\n",
    "单行注释用#\n",
    "\n",
    "    # 程序运行时该注释不会显示\n",
    "\n",
    "多行注释用三对引号\n",
    "\n",
    "    \"\"\"\n",
    "    多行注释\n",
    "    多行注释\n",
    "    \"\"\"\n",
    "\n",
    "### 缩进与空格\n",
    "* python最具特色的就是使用缩进来表示代码块，不需要使用大括号`{}`。\n",
    "缩进的空格数是可变的，但是同一个代码块的语句必须包含相同的缩进空格数，为了统一规范一般用4个空格。\n",
    "* 为了代码的整体美观、便于阅读和便于维护，用空格隔开不同的元素\n",
    "\n",
    "### 代码换行\n",
    "* Python 通常是一行写完一条语句，但如果语句很长，我们可以使用反斜杠`\\`来实现多行语句，例如："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "item_one = item_two = item_three =1\n",
    "total = item_one + \\\n",
    "        item_two + \\\n",
    "        item_three\n",
    "\n",
    "total"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 在`[]` `{}`或`()`中的多行语句，不需要使用反斜杠`\\`，例如："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['item_one', 'item_two', 'item_three', 'item_four', 'item_five']"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "total = ['item_one', 'item_two', 'item_three',\n",
    "        'item_four', 'item_five']\n",
    "total"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 一行显示多条语句,Python可以在同一行中使用多条语句，语句之间使用分号`;`分割:\n",
    "```\n",
    "import sys; x = 'runoob'; sys.stdout.write(x + '\\n')\n",
    "```\n",
    "\n",
    "* 空行  \n",
    "    函数之间或类的方法之间用空行分隔，表示一段新的代码的开始。类和函数入口之间也用一行空行分隔，以突出函数入口的开始。\n",
    "    空行与代码缩进不同，空行并不是Python语法的一部分。书写时不插入空行，Python解释器运行也不会出错。但是空行的作用在于分隔两段不同功能或含义的代码，便于日后代码的维护或重构。\n",
    "\n",
    ">在Python中的变量不需要声明。每个变量在使用前都必须赋值，变量赋值以后该变量才会被创建。**对象有类型，变量无类型**\n",
    "\n",
    "## 数据类型\n",
    "### Number（数字）\n",
    "* int\n",
    "* float\n",
    "* bool  \n",
    "    `True` `False`，首字母必须大写\n",
    "* complex\n",
    "    1+2j\n",
    "\n",
    "### String\n",
    "可以索引和切片，不能被改变\n",
    "\n",
    "### List\n",
    "有序，可以索引、切片、可变\n",
    "\n",
    "### Tuple\n",
    "可以索引和切片，不能被改变\n",
    "\n",
    "### Dictionary --- {key:value}\n",
    "无序，元素是一对键值\n",
    "\n",
    "### Set --- {1,'a'}\n",
    "集合是一个无序不重复元素的序列。创建一个空集合必须用`set()`而不是`{}`，因为`{}`是用来创建一个空字典。\n",
    "\n",
    ">id()可以查看内存地址\n",
    ">type()查看数据类型"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 变量\n",
    "在Python中，有这样一句话是非常重要的：**对象有类型，变量无类型**。\n",
    "Python 中的变量不需要声明。每个变量在使用前都必须赋值，变量赋值以后该变量才会被创建。\n",
    "在 Python 中，变量就是变量，它没有类型，我们所说的\"类型\"是变量所指的内存中对象的类型。\n",
    "等号`=`用来给变量赋值。\n",
    "等号`=`运算符左边是一个变量名,等号`=`运算符右边是存储在变量中的值"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Python3运算符\n",
    "* 算术运算符\n",
    "* 比较（关系）运算符\n",
    "* 赋值运算符\n",
    "* 逻辑运算符\n",
    "* 位运算符\n",
    "* 成员运算符\n",
    "* 身份运算符\n",
    "* 运算符优先级\n",
    "\n",
    "### 算术运算符\n",
    "\n",
    "    >>> a = 10\n",
    "    >>> b = 4\n",
    "\n",
    "| 运算符 |  描述  | 实例  |                                     结果                                      |\n",
    "| :----: | :----: | :---: | :---------------------------------------------------------------------------: |\n",
    "|   +    |   加   |  a+b  |                                      14                                       |\n",
    "|   -    |   减   |  a-b  |                                       6                                       |\n",
    "|   *    |   乘   |  a*b  |                                      40                                       |\n",
    "|   /    |   除   |  a/b  |      <span style=\"color:blue;\" title=\"结果的类型总是为float\">2.5</span>       |\n",
    "|   %    |  取余  |  a%b  |                                       2                                       |\n",
    "|   **   |   幂   | a**b  | <span style=\"color:blue;\" title=\"若数字太长则会用科学计数法显示\">10000</span> |\n",
    "|   //   | 取整除 | a//b  |                                       2                                       |\n",
    "\n",
    ">凡是浮点型参与计算，结果都为浮点型"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### 比较运算符\n",
    "\n",
    "    >>> a = 10\n",
    "    >>> b = 4\n",
    "\n",
    "| 运算符 |   描述   | 实例  | 结果  |\n",
    "| :----: | :------: | :---: | :---: |\n",
    "|   ==   |   等于   | a==b  | False |\n",
    "|   !=   |  不等于  | a!=b  | True  |\n",
    "|   >    |   大于   |  a>b  | True  |\n",
    "|   <    |   小于   |  a<b  | False |\n",
    "|   >=   | 大于等于 | a>=b  | False |\n",
    "|   <=   | 小于等于 | a<=b  | False |\n",
    "\n",
    "### 赋值运算符\n",
    "\n",
    "| 运算符 | 实例  |  描述  |\n",
    "| :----: | :---: | :----: |\n",
    "|   =    | c=a+b |        |\n",
    "|   +=   | c+=a  | c=c+a  |\n",
    "|   -=   | c-=a  | c=c-a  |\n",
    "|   *=   | c*=a  | c=c*a  |\n",
    "|   /=   | c/=a  | c=c/a  |\n",
    "|   %=   | c%=a  | c=c%a  |\n",
    "|  **=   | c**=a | c=c**a |\n",
    "|  //=   | c//=a | c=c//a |"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### 位运算符\n",
    ">按位运算符是把数字看作二进制来进行计算的。\n",
    "\n",
    "| 运算符 |                                              描述                                               |\n",
    "| :----: | ----------------------------------------------------------------------------------------------- |\n",
    "|   &    | 按位与运算符；参与运算符的两个值，如果两个相应位都为1，则该位的结果为1，否则为0                 |\n",
    "| 按位或 | 按位或运算符：只要对应的二个二进位有一个为1时，结果位就为1。                                    |\n",
    "|   ^    | 按位异或运算符；当两队应的二进位相异时，结果为1                                                 |\n",
    "|   ~    | 按位取反运算符：对数据的每个二进制位取反,即把1变为0,把0变为1                                    |\n",
    "|   <<   | 左移动运算符：运算数的各二进位全部左移若干位，由\"<<\"右边的数指定移动的位数，高位丢弃，低位补0。 |\n",
    "|   >>   | 右移动运算符：把\">>\"左边的运算数的各二进位全部右移若干位，\">>\"右边的数指定移动的位数            |\n",
    "\n",
    ">按位或运算符`|`，md表格不能打出`|`\n",
    "\n",
    "### 逻辑运算符\n",
    "`and`, `or`, `not`\n",
    "\n",
    "### 成员运算符\n",
    "`in`, `not in`\n",
    "\n",
    "### 身份运算符\n",
    "`is`, `is not`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 运算符优先级\n",
    "\n",
    "| 优先级 |                             运算符                              |\n",
    "| :----: | :-------------------------------------------------------------: |\n",
    "|   1    |                              `**`                              |\n",
    "|   2    | `~` <span style=\"color:blue;\" title=\"一元加号和减号\">+ -</span> |\n",
    "|   3    |                        `*` `/` `%` `//`                         |\n",
    "|   4    |                             `+` `-`                             |\n",
    "|   5    |                            `>>` `<<`                            |\n",
    "|   6    |                               `&`                               |\n",
    "|   7    |                           `^` 按位或                            |\n",
    "|   8    |                         `<=` `<>` `>=`                          |\n",
    "|   9    |                        `<``>` `==` `!=`                         |\n",
    "|   10   |            `=` `%=` `/=` `//=` `-=` `+=` `*=` `**=`             |\n",
    "|   11   |                          `is` `is not`                          |\n",
    "|   12   |                          `in` `not in`                          |\n",
    "|   13   |                        `not` `or` `and`                         |\n",
    "\n",
    "### float精度问题"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.30000000000000004"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "text/plain": [
       "5.551115123125783e-17"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "0.1 + 0.2              # -->\n",
    "\n",
    "0.1 + 0.1 + 0.1 - 0.3  # -->"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "原因在于十进制和二进制的转换上，电脑用的是二进制进行计算，上面的例子中，我们输入的是十进制，她就要把十进制的数转化为二进制，然后再计算。但是，在转化中，浮点数转化为二进制，就出问题了。\n",
    "\n",
    "例如十进制的0.1，转化为二进制是：0.0001100110011001100110011001100110011001100110011...\n",
    "\n",
    "也就是说，转化为二进制后，不会精确等于十进制的0.1。同时，计算机存储的位数是有限制的，所以，就出现上述现象了。\n",
    "这种问题不仅仅是Python中有，所有支持浮点数运算的编程语言都会遇到，它不是Python的bug。\n",
    ">使用numPy包和其它用于数学和统计学的包，可以解决上述问题"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## 常用数学函数\n",
    "\n",
    "|     函数     |   代码实例    | 返回值 |                                描述                                 |\n",
    "| :----------: | :-----------: | :----: | :-----------------------------------------------------------------: |\n",
    "|    abs(x)    |   abs(-1.2)   |  1.2   |     返回 x（数字）的绝对值，如果参数是一个复数，则返回它的大小      |\n",
    "|    max(x)    |   max(1,2)    |   2    |                返回给定参数的最大值，参数可以为序列                 |\n",
    "|    min(x)    |   min(1,2)    |   1    |                返回给定参数的最小值，参数可以为序列                 |\n",
    "| round(x[,n]) | round(3.14,1) |  3.1   | 返回浮点数x的四舍五入值,第二个参数规定保留的小数位数，不写则默认为0 |"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### math模块\n",
    "math是标准库之一，所以不用安装，可以直接使用。使用方法是：\n",
    "\n",
    "    >>> import math\n",
    "\n",
    "|   函数   |     代码实例      |       返回值       |                   描述                    |\n",
    "| :------: | :---------------: | :----------------: | :---------------------------------------: |\n",
    "| ceil(x)  |  math.ceil(1.2)   |         2          |     返回一个大于或等于 x 的的最小整数     |\n",
    "| floor(x) | math.floor(-1.2)  |         -2         |     返回一个小于或等于 x 的的最小整数     |\n",
    "|  exp(x)  | math.exp(math.pi) | 23.140692632779267 |         返回x的指数,e<sup>x</sup>         |\n",
    "| fabs(x)  |  math.fabs(-1.2)  |        1.2         | 返回数字的绝对值,只对浮点型跟整型数值有效 |\n",
    "| sqrt(x)  |  math.sqrt(100)   |         10         |             返回数字x的平方根             |\n",
    "\n",
    "`dir(module)`：查看命令的属性和方法  \n",
    "`help()`：查看帮助"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### 随机数函数\n",
    "随机数可以用于数学，游戏，安全等领域中，还经常被嵌入到算法中，用以提高算法效率，并提高程序的安全性。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import random"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* choice(seq)方法返回一个列表，元组或字符串的随机项"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'u'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "random.choice('Runoob')         # -->\n",
    "random.choice([1, 2, 3, 5, 9])  # -->"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* randrange ([start,] stop [,step])方法返回指定递增基数集合中的一个随机数，基数缺省值为1。\n",
    "    * start -- 指定范围内的开始值，包含在范围内。\n",
    "    * stop -- 指定范围内的结束值，不包含在范围内。\n",
    "    * step -- 指定递增基数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "21"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 从 1-100 中选取一个奇数\n",
    "random.randrange(1, 100, 2)  # -->"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "65"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 从 0-99 选取一个随机数\n",
    "random.randrange(100)  # -->"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.8046523334845248"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# random() 方法返回随机生成的一个实数，它在[0,1)范围内。\n",
    "random.random()  # -->"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* random.seed([x])改变随机数生成器的种子,此方法没有返回值。参数x 改变随机数生成器的种子seed。不必特别去设定seed，Python会选择seed。\n",
    "* random.shuffle(lst)方法将列表和元组的所有元素随机排序。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[20, 5, 16, 10]"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list1 = [20, 16, 10, 5]\n",
    "random.shuffle(list1)\n",
    "list1  # -->"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6.1802185380961685"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# uniform(x, y)在[x,y]范围内,随机生成一个实数。\n",
    "random.uniform(5, 10)  # -->"
   ]
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.4rc1"
  },
  "toc": {
   "nav_menu": {},
   "number_sections": false,
   "sideBar": true,
   "skip_h1_title": false,
   "toc_cell": false,
   "toc_position": {
    "height": "839px",
    "left": "0px",
    "right": "1669px",
    "top": "107px",
    "width": "251px"
   },
   "toc_section_display": "none",
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": "15",
    "lenType": "10",
    "lenVar": "60"
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
